import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Not, Between, In } from 'typeorm';
import { QrcodeQrcodeEntity } from '../entity/qrcode';
import { PluginService } from '../../plugin/service/info';
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import { QrcodeBehaveLogEntity } from '../entity/behaveLog';
import { DictInfoEntity } from '../../dict/entity/info';
import { AppointmentInfoEntity } from '../../appointment/entity/info';
import { UserInfoEntity } from '../../user/entity/info';


/**
 * 二维码信息
 */
@Provide()
export class QrcodeDataboardService extends BaseService {
  @InjectEntityModel(QrcodeQrcodeEntity)
  qrcodeQrcodeEntity: Repository<QrcodeQrcodeEntity>;

  @Inject()
  pluginService: PluginService;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @InjectEntityModel(QrcodeBehaveLogEntity)
  qrcodeBehaveLogEntity: Repository<QrcodeBehaveLogEntity>;

  @InjectEntityModel(DictInfoEntity)
  dictInfoEntity: Repository<DictInfoEntity>;

  @InjectEntityModel(AppointmentInfoEntity)
  AppointmentInfoEntity: Repository<AppointmentInfoEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @Inject()
  ctx;

  /**
   * 获取达人的销售数据
   */
  async getSalesAppointConvertBoardForDaren(param: {
    startTime?: string; // 开始时间，可选
    endTime?: string;   // 结束时间，可选
  }) {
    // 初始化结果数组
    let result = [];

    // 处理时间范围
    let startDate = new Date();
    let endDate = new Date();
    
    if (param.startTime && param.endTime) {
      // 如果提供了时间范围，使用提供的时间
      startDate = new Date(param.startTime);
      endDate = new Date(param.endTime);
      endDate.setHours(23, 59, 59, 999);
    } else {
      // 默认最近7天
      startDate.setDate(startDate.getDate() - 6); // 减6天得到最近7天
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
    }
    
    // 查询达人不为空的二维码
    const sales = await this.qrcodeQrcodeEntity.find({
      where: {
        daren: Not('')
      }
    })
    // 查询admin数组
    const adminArr = await this.baseSysUserEntity.find({})
    // 查询字典数组
    const dictArr = await this.dictInfoEntity.find({
      where: {
        typeId: 21
      }
    })
    // 查询日期内的行为数据
    const logArr = await this.qrcodeBehaveLogEntity.find({
      where: {
        createTime: Between(startDate, endDate)
      }
    })

    // 查看预约的人数
    const appoint = await this.AppointmentInfoEntity.find({
      where: {
        createTime: Between(startDate, endDate)
      }
    })

    // 获取预约人的id数组
    const studentIds = appoint.map(ap => ap.studentId)

    // 遍历预约的人数查看预约人注册ID
    const student = await this.userInfoEntity.find({
      where: {
        id: In(studentIds)
      }
    })

    
    // 数据初始化
    for (const qrcode of sales) {

      // 查找logArr跟qrCodeId相同的数组
      const behaveArr = logArr.filter(item => item.qrcodeId == qrcode.id)
      // 统计去重的海报打开数
      const posterOpenNum = behaveArr.filter(item => item.eventType == 'openPage').length
      // 统计去重的注册数
      const registOpenids = new Set(behaveArr.filter(item => item.eventType == 'regist').map(item => item.openid));
      const registNum = registOpenids.size;
      // 统计去重的提交表单数
      const submitOpenids = new Set(behaveArr.filter(item => item.eventType == 'submitForm').map(item => item.openid));
      const submitNum = submitOpenids.size;
      // 统计预约人数
      const appointNum = student.filter(item => item.qrcodeId == qrcode.id).length

      // 添加该店铺的合计行
      result.push({
        qrCodeId: qrcode.id,
        salesName: adminArr.find(item => item.id == qrcode.adminId)?.nickName, // 销售名称
        downSales: qrcode.daren, // 达人名称
        channelName: dictArr.find(item => item.id == qrcode.channelId)?.name, //渠道名称
        // 海报打开数
        posterOpenNum: posterOpenNum,
        // 注册数
        registNum: registNum,
        // 提交表单数
        submitNum: submitNum,
        // 预约数
        appointNum: appointNum,
        // 转化数
        convertNum: 0,
      });
    }
    
    return result;
  }
}
